import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:hxdj/common/dio/dio_http.dart';
import 'package:hxdj/common/utils/my_event_bus_util.dart';
import 'package:hxdj/message/message_page/message_viewmodel.dart';
import 'package:hxdj/message/rongcloud/rc_chat/model/rc_chat_model.dart';
import 'package:hxdj/message/rongcloud/rc_engine_manager.dart';
import 'package:provider/provider.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';

class RCChatGlobalModel extends ChangeNotifier {
  //保存当前消息的Map
  final Map<String, List<ChatMessageBaseModel>?> chatMessageListMap = {};

  //获取与当前人的聊天信息
  Map<String, dynamic> imUserInfo = {};

  late StreamSubscription onEventResult;

  RCChatGlobalModel() {
    //这里可以监听接收消息的数据
    onEventResult = MyEventBusUtil.onEventResult((value) {
      if (value.tag == MyEventBusTag.onMessageReceived) {
        //接收到信息

        Map<String, String> arg = Map<String, String>.from(value.result);
        late String left = arg['left']!;
        if (left == "0") {
          // 更新最近会话
          Map<String, dynamic> messageMap = json.decode(arg['message']!);
          RCIMIWMessage messageModel = RCIMIWMessage.fromJson(messageMap);

          insertMessage(messageModel, messageMap: messageMap);
        }
      }
    });
  }

  //清楚未读消息
  clearUnreadCount(String targetId) async {
    List<ChatMessageBaseModel>? messageList = chatMessageListMap[targetId] ?? [];
    //清除未读消息
    if (messageList.isNotEmpty) {
      int isSuccess = await RCEngineManager().clearUnreadCount(targetId, messageList.first.sentTime!,
          callback: IRCIMIWClearUnreadCountCallback(onUnreadCountCleared: (int? code) {
        //更新下消息列表的更新最近的会话 DateTime.now().millisecondsSinceEpoch + 5000,
        debugPrint("更新下消息列表的更新最近的会话 code == $code");
        //找到对应的会话, 进行更新
      }));
      debugPrint("clearUnreadCount  isSuccess == $isSuccess");
    }
  }

  clearData() {
    chatMessageListMap.clear();

    notifyListeners();
  }

  //保存信息
  void setMessageList(String conversationID, List<ChatMessageBaseModel> messageList) {
    List<ChatMessageBaseModel>? oldMessageList = chatMessageListMap[conversationID] ?? [];
    if (messageList.isNotEmpty) {
      // for (ChatMessageBaseModel element in messageList) {}
      oldMessageList.addAll(messageList);
    }

    chatMessageListMap[conversationID] = oldMessageList;
    notifyListeners();
    //清空已读消息
    clearUnreadCount(conversationID);
  }

  List<ChatMessageBaseModel>? getMessageList(String conversationID) {
    final dataMessageList = (chatMessageListMap[conversationID]?.reversed.toList() ?? []).toList();

    final List<ChatMessageBaseModel> valueList = [];
    //为了判断是否展示当前发送的时间
    ChatMessageBaseModel? temp;

    for (ChatMessageBaseModel messageModel in dataMessageList) {
      if (temp == null) {
        //第一条数据, 展示时间
        temp = messageModel;
        messageModel.isShowTime = true;
      } else {
        // temp的时间, 跟messageModel的时间去对比, 大于15分钟就展示时间
        // 消息的接收时间（Unix 时间戳、毫秒）
        int? tempMessageReceivedTime = temp.receivedTime;

        int? meessageReceivedTime = messageModel.receivedTime;

        if ((meessageReceivedTime! - tempMessageReceivedTime!) > 5 * 60 * 1000) {
          messageModel.isShowTime = true;
        } else {
          messageModel.isShowTime = false;
        }
        temp = messageModel;
      }

      valueList.add(messageModel);
    }

    return valueList.reversed.toList();
  }

  //发送文本信息
  sendMessageText(BuildContext context, String targetId, String text) async {
    final bool isSuccess = await filterMessage(text, "RC:TxtMsg", targetId);
    if (!isSuccess) return;
    RCEngineManager().sendTextMessage(targetId, text,
        callback: RCIMIWSendMessageCallback(onMessageSent: (int? code, RCIMIWMessage? message) {
          debugPrint("code.text =  $code");
          debugPrint("message.text =  ${message!.receivedStatus}");
        }, onMessageSaved: (RCIMIWMessage? message) {
          //更新最近的会话
          Provider.of<MessageViewModel>(context, listen: false).updateRecentConversationList(targetId, isNeedAll: true);
          //插入消息
          insertMessage(message!);
        }));
  }

  // 插入一条消息, 接收的消息是一个map, 就直接放这里了
  insertMessage(RCIMIWMessage message, {Map<String, dynamic>? messageMap}) {
    ChatMessageBaseModel? messageModel;

    RCIMIWMessageType? messageType = message.messageType;

    if (messageMap != null) {
      messageType = RCIMIWMessageType.values[messageMap['messageType']];
    }

    switch (messageType) {
      case RCIMIWMessageType.text:
        messageModel = ChatMessageTextModel.fromJson(messageMap ?? message.toJson());
        break;
      case RCIMIWMessageType.image:
        messageModel = ChatMessageImageModel.fromJson(messageMap ?? message.toJson());
        break;
      default:
        messageModel = ChatMessageBaseModel.fromJson(messageMap ?? message.toJson());
    }

    List<ChatMessageBaseModel>? oldMessageList = chatMessageListMap[message.targetId] ?? [];
    // for (ChatMessageBaseModel element in messageList) {}
    oldMessageList.insert(0, messageModel);
    chatMessageListMap[message.targetId!] = oldMessageList;

    notifyListeners();
  }

  //过滤下敏感信息
  Future<bool> filterMessage(String content, String messageType, String receiveImUser) async {
    // 去请求服务器数据.
    Map<String, dynamic> resultMap = await DioHttpManager().request(MyApi.apiV1ChatSend,
        method: DioHttpManager.post,
        data: {"message_type": messageType, "content": content, "receive_im_user": receiveImUser});
    if (resultMap['code'] == 0) {
      return true;
    } else {
      EasyLoading.showToast(resultMap['msg']);
      return false;
    }
  }
}
